<?php
/**
 *
 * 用户事件响应器
 *
 */
class User_Handler 
{
	private static $_instance = NULL;

	public static function instance ($event)
	{
		if (NULL === self::$_instance)
		{
			$class = __CLASS__;
			self::$_instance = new $class();
		}

		return self::$_instance;
	}

	public function __construct ()
	{
		//
	}

	/*
	 * 处理事件
	 */
	public function handle ($event, $obj)
	{
		switch ($event)
		{
        //
        // 用户创建成功
        //
        case Kohana::config('events.user.created') :

            $user_info = (array) $obj;
            $uid       = Arr::get($user_info, 'uid');
            $utype     = Arr::get($user_info, 'utype');
            $message   = Kohana::config('user.message.welcome.'.$utype);

            Notice::factory('notification')
                ->to($uid)
                ->message($message)
                ->send();

            break;

		//
		// 买家给商铺留言
		// 
		case Kohana::config('events.message.new_on_shop') :
			$p =& $obj;
			$user_id  = $p['user_id'];
			$shop_id  = $p['target_id'];
			track_user::add($user_id, $shop_id, 0, 'message', 0);
			break;

		//
		// 买家咨询商品
		// 
		case Kohana::config('events.message.new_on_goods') :
			$p =& $obj;
			$user_id  = $p['user_id'];
			$goods_id = $p['target_id'];
			$shop_id  = goods::shop_id ($goods_id);
			track_user::add($user_id, $shop_id, $goods_id, 'consult', $goods_id);
			break;

		//
		// 他人代付成功
		//
		case Kohana::config('events.pbo.success') :
			$order_info = $obj;
			$order_id    = Order_Core::formated_order_id($order_info['id']);
			$create_time = date("Y-m-d H:i:s", $order_info['create_time']);
			$pay_time    = date("Y-m-d H:i:s", $order_info['pay_time']);
			$uid         = (int) $order_info['uid'];
			$user_info   = User::instance($uid)->get_user_info();
			$passport    = $user_info['passport'];
			$mobile      = Arr::get($user_info,'mobile',NULL);
			$name        = $user_info['nickname'];

			if (!empty($mobile) && Kohana::config('pbo.send_sms') == TRUE)
			{
				Notice::factory('sms')->to($mobile)
					->message("尊敬的{$name}: 您的订单{$order_id}（创建于{$create_time})于{$pay_time}由他人代付成功!")
					->send();

				events::notify(Kohana::config('events.system.notice'),
					array(
						'uid'    => $uid,
						'action' => 'pbo_pay',
						'value'  => $order_id,
						'comment'=> '短信通知:他人代付订单支付成功('.$pay_time.')',
						'time'   => time(),
					));
			}

			if (!empty($passport) && Kohana::config('pbo.send_mail') == TRUE)
			{
				Notice::factory('email')
						->to($passport)
						->subject('测试邮件')
						->message("user:{$name},order{$order_id},create_time{$create_time},pay_time{$pay_time}!")
						->send();
			}
			break;
			

		default: 
			break;
		}

		return FALSE;
	}
}
